#include <event2/event.h>
#include <event2/http.h>
#include <event2/buffer.h>
#include <event2/util.h>
#include <iostream>
#include <fstream>

#define SERVER_PORT 8080

// 文件下载回调函数
void file_download_cb(struct evhttp_request *req, void *arg) {
    const char *file_path = "/home/arv000/Desktop/C++.zip";  // 待下载文件路径
    std::ifstream file(file_path, std::ios::binary);

    if (!file) {
        evhttp_send_error(req, HTTP_NOTFOUND, "File not found");
        return;
    }

    // 读取文件内容到 evbuffer
    struct evbuffer *evb = evbuffer_new();
    if (!evb) {
        evhttp_send_error(req, HTTP_INTERNAL, "Failed to allocate memory");
        return;
    }

    file.seekg(0, std::ios::end);
    size_t file_size = file.tellg();
    file.seekg(0, std::ios::beg);

    char *buffer = new char[file_size];
    file.read(buffer, file_size);
    evbuffer_add(evb, buffer, file_size);
    delete[] buffer;

    // 设置 HTTP 头
    evhttp_add_header(evhttp_request_get_output_headers(req), "Content-Type", "application/octet-stream");
    evhttp_add_header(evhttp_request_get_output_headers(req), "Content-Disposition", "attachment; filename=\"test_file.txt\"");

    // 发送响应
    evhttp_send_reply(req, HTTP_OK, "OK", evb);
    evbuffer_free(evb);
}

int main() {
    struct event_base *base;
    struct evhttp *http;
    struct evhttp_bound_socket *handle;

    // 初始化 event_base
    base = event_base_new();
    if (!base) {
        std::cerr << "Failed to create event base\n";
        return 1;
    }

    // 创建 HTTP 服务器
    http = evhttp_new(base);
    if (!http) {
        std::cerr << "Failed to create evhttp\n";
        event_base_free(base);
        return 1;
    }

    // 绑定监听端口
    handle = evhttp_bind_socket_with_handle(http, "0.0.0.0", SERVER_PORT);
    if (!handle) {
        std::cerr << "Failed to bind port " << SERVER_PORT << "\n";
        evhttp_free(http);
        event_base_free(base);
        return 1;
    }

    std::cout << "HTTP server started on port " << SERVER_PORT << "\n";

    // 注册下载回调
    evhttp_set_cb(http, "/download", file_download_cb, nullptr);

    // 事件循环
    event_base_dispatch(base);

    // 清理资源
    evhttp_free(http);
    event_base_free(base);

    return 0;
}
